<template>
  <div class="app-container">
    <div class="top">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item>
          <el-checkbox
            v-model="queryParams.queryType"
            label="与我相关"
            border
            size="small"
            true-label="user"
            false-label="workshop"
            class="related-me"
            @change="handleQuery"
          ></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox
            v-model="queryParams.queryQcTask"
            label="品控关注"
            border
            size="small"
            true-label="1"
            false-label=""
            class="related-me"
            @change="handleQuery"
          ></el-checkbox>
        </el-form-item>
        <el-form-item prop="taskName" class="width1">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item class="width1"> -->
        <organizationCascader
          class="organization-cascader"
          :clearData="{
            factory: true,
            workshop: true,
            line: true,
          }"
          :arrData="queryParams"
          :showData="{
            factory: true,
            workshop: true,
            line: true,
            workSection: false,
          }"
          :isAllList="true"
          @change="queryParamsChange"
        ></organizationCascader>
        <!-- </el-form-item> -->
        <el-form-item prop="taskType" class="width1">
          <el-select
            v-model="queryParams.taskType"
            placeholder="请选择任务类型"
            clearable
            size="small"
          >
            <el-option
              v-for="item in dict.taskType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" class="width1">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="item in taskStatusOptions"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
            <el-option key="timeout" label="超时时长>0" value="timeout">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="time" class="width2">
          <el-date-picker
            v-model="queryParams.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="operate">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['taskMgmt:center:add']"
          >新增
        </el-button>
        <el-button
          type="default"
          icon="el-icon-finished"
          size="mini"
          @click="handleApproveBatch()"
          v-hasPermi="['taskMgmt:center:examine']"
          :disabled="approveBatchDisabled"
          >审核
        </el-button>
        <el-button
          type="default"
          icon="el-icon-close"
          size="mini"
          @click="handleClose()"
          v-hasPermi="['taskMgmt:center:close']"
          :disabled="closeBatchDisabled"
          >关闭
        </el-button>
        <el-button
          type="default"
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['taskMgmt:center:export']"
          >导出
        </el-button>
      </div>
    </div>
    <el-table
      ref="Table"
      :data="list"
      tooltip-effect="dark"
      style="width: 100%"
      height="calc(100% - 88px - 50px)"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="任务ID" prop="id"> </el-table-column>
      <el-table-column label="任务名称" prop="taskName">
        <template slot-scope="{ row }">
          <el-button type="text" @click.stop="handleDetail(row)">{{
            row.taskName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" prop="taskType" width="140">
        <template slot-scope="{ row }">
          {{ taskTypeDictObj[row.taskType] }}
        </template>
      </el-table-column>
      <el-table-column label="品控关注" prop="isConcernedTask">
        <template slot-scope="{ row }">
          {{ row.isConcernedTask == "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="车间" prop="ownedWorkshopName"> </el-table-column>
      <el-table-column label="产线" prop="ownedProductionLineName" width="160">
      </el-table-column>
      <el-table-column label="执行人">
        <template slot-scope="{ row }">
          {{ getOperatorLabel(row) }}
        </template>
      </el-table-column>
      <el-table-column label="审核人" prop="auditorName">
        <!-- <template slot-scope="{ row }">
          {{ postManageDictObj[row.auditor] || row.auditorName }}
        </template> -->
      </el-table-column>
      <el-table-column
        label="当前班组"
        prop="groupName"
        width="130"
      ></el-table-column>
      <el-table-column label="任务时间" width="160">
        <template slot-scope="{ row }">
          <div>{{ row.actualExecuteStartTime + " - " }}</div>
          <div>{{ row.actualExecuteEndTime }}</div>
        </template>
      </el-table-column>
      <el-table-column label="超时时长(小时)">
        <template slot-scope="{ row }">
          {{ row.taskTimeoutHour ? row.taskTimeoutHour + "小时" : "" }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="{ row }">
          <span :class="'status-' + row.status">{{
            taskStatusDictObj[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="120"
        fixed="right"
      >
        <!-- 与我相关的任务，才有操作权限 -->
        <template slot-scope="{ row }">
          <!-- 显示规则：状态为待执行或已反驳或执行中,并且没有转办人(即没有被转办过)或转办人是登陆人 -->
          <el-button
            v-if="
              buttonPermi(['taskMgmt:center:execute'], row.hasExecPower == 'Y')
            "
            type="text"
            @click.stop="handleExecute(row)"
            >执行</el-button
          >
          <!-- 执行转办，显示规则：状态为待执行或已反驳或执行中，以及该条数据转办人为null或当前登陆人 -->
          <el-button
            v-if="
              buttonPermi(['taskMgmt:center:transfer'], row.hasExecPower == 'Y')
            "
            type="text"
            @click.stop="handleTransfer(row)"
            >转办</el-button
          >
          <!-- 显示规则：状态为待审核，审核人为当前登陆人 -->
          <el-button
            v-if="
              buttonPermi(
                ['taskMgmt:center:examine'],
                row.hasAuditorPower == 'Y'
              )
            "
            type="text"
            @click.stop="handleApprove(row)"
            >审核</el-button
          >
          <!-- 审核转办，显示规则：状态为待审核，以及该条数据的审核人是当前登陆人 -->
          <el-button
            v-if="
              buttonPermi(
                ['taskMgmt:center:approveTransfer'],
                row.hasAuditorPower == 'Y'
              )
            "
            type="text"
            @click.stop="handleTransfer(row)"
            >转办</el-button
          >
          <!-- 显示规则：状态为待执行，执行中，已驳回 -->
          <el-button
            v-if="
              buttonPermi(['taskMgmt:center:close'], row.hasExecPower == 'Y')
            "
            type="text"
            @click.stop="handleClose(row)"
            >关闭</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getList"
    />

    <!-- 新增任务 -->
    <AddDialog
      :visible.sync="addDialog.visible"
      :row="addDialog.row"
      :disabled="addDialog.disabled"
      @refresh="getList"
    ></AddDialog>

    <!-- 转办 -->
    <TransferDailog
      :visible.sync="transferDailog.visible"
      :row="transferDailog.row"
      @refresh="getList"
    ></TransferDailog>

    <!-- 任务执行 -->
    <ExecuteDailog
      :visible.sync="executeDailog.visible"
      :row="executeDailog.row"
      @refresh="getList"
    ></ExecuteDailog>

    <!-- 审核 -->
    <ApproveDailog
      :visible.sync="approveDailog.visible"
      :row="approveDailog.row"
      @refresh="getList"
    ></ApproveDailog>

    <!-- 关闭 -->
    <CloseDailog
      :visible.sync="closeDailog.visible"
      :rows="closeDailog.rows"
      @refresh="getList"
    ></CloseDailog>

    <!-- 批量审核 -->
    <ApproveTaskBatchDialog
      :visible.sync="approveTaskBatchDialog.visible"
      :rows="approveTaskBatchDialog.rows"
      @refresh="getList"
    ></ApproveTaskBatchDialog>

    <!-- 任务详情 -->
    <DetailDialog
      :visible.sync="detailDailog.visible"
      :row="detailDailog.row"
    ></DetailDialog>
  </div>
</template>
<script>
import organizationCascader from "@/views/components/organizationCascader";
import { getTaskCenterList, exportTaskList } from "@/api/taskMgmt/center";
import AddDialog from "./addDialog";
import DetailDialog from "./detailDialog";
import TransferDailog from "../components/transferTaskDialog";
import ExecuteDailog from "../components/executeTaskDialog";
import ApproveDailog from "../components/approveTaskDialog";
import CloseDailog from "../components/closeTaskDialog";
import ApproveTaskBatchDialog from "../components/approveTaskBatchDialog";
import { downloadFile } from "@/utils/file";
import { checkPermi } from "@/utils/permission";
import { mapState, mapMutations } from "vuex";
// 任务中心列表展示的所有状态(待执行，待审核，已驳回，已超时，执行中)
const AllStatus = ["0", "1", "2", "3", "5"];
export default {
  name: "Center",
  components: {
    organizationCascader,
    AddDialog,
    DetailDialog,
    TransferDailog,
    ExecuteDailog,
    ApproveDailog,
    CloseDailog,
    ApproveTaskBatchDialog,
  },
  dicts: ["taskType", "taskStatus", "PostManage"],
  data() {
    return {
      queryParams: {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
        time: null,
        queryType: "user", //默认与我相关
        queryQcTask: "",
      },
      list: [],
      loading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      // 批量审批按钮的disabled
      approveBatchDisabled: true,
      // 批量关闭按钮的disabled
      closeBatchDisabled: true,
      addDialog: {
        visible: false,
        row: null,
        disabled: false,
      },
      transferDailog: {
        visible: false,
        row: null,
      },
      executeDailog: {
        visible: false,
        row: null,
      },
      approveDailog: {
        visible: false,
        row: null,
      },
      closeDailog: {
        visible: false,
        rows: [],
      },
      approveTaskBatchDialog: {
        visible: false,
        rows: [],
      },
      detailDailog: {
        visible: false,
        row: null,
      },
      exportLoading: false,
      isDeactivate: false,
    };
  },
  computed: {
    ...mapState({
      taskAnalysisDetail: (state) => state.workbench.taskAnalysisDetail,
    }),
    taskStatusOptions() {
      if (!this.dict.taskStatus) {
        return [];
      }
      // 只展示待执行，待审核，已驳回，执行中
      return this.dict.taskStatus.filter((ele) =>
        AllStatus.includes(ele.codevalue)
      );
    },
    taskTypeDictObj() {
      return this.dictToMap(this.dict.taskType);
    },
    taskStatusDictObj() {
      return this.dictToMap(this.dict.taskStatus);
    },
    postManageDictObj() {
      return this.dictToMap(this.dict.PostManage);
    },
  },

  activated() {
    if (this.taskAnalysisDetail) {
      this.queryParams = Object.assign(
        {},
        this.queryParams,
        this.taskAnalysisDetail
      );
      this.getList();
    }
  },

  deactivated() {
    this.SET_TASKANALYSIS_DETAIL(null);
  },

  created() {
    // 默认获取第一个工厂-车间-产线
    const results = this.getOwnFirstLine();
    this.queryParams.factoryDeptCode = results[0]?.factoryDeptCode || "";
    this.queryParams.workshopCode = results[1]?.workshopCode || "";
    this.queryParams.lineCode = results[2]?.lineCode || "";
    this.queryParams.lineId = results[2]?.lineId || "";
    if (this.taskAnalysisDetail) {
      this.queryParams = Object.assign(
        {},
        this.queryParams,
        this.taskAnalysisDetail
      );
    }
    //获取列表数据
    this.getList();
  },
  methods: {
    ...mapMutations("workbench", ["SET_TASKANALYSIS_DETAIL"]),
    // 列表按钮显示权限
    buttonPermi(permis, flag) {
      return checkPermi(permis) && flag;
    },
    getList() {
      this.loading = true;
      this.approveBatchDisabled = true;
      this.closeBatchDisabled = true;
      const { pageNum, pageSize } = this.pager;
      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
        time,
        queryType,
        queryQcTask,
      } = this.queryParams;
      const params = {
        query: {
          taskName,
          ownedFactory: factoryDeptCode,
          ownedWorkshop: workshopCode,
          ownedProductionLine: lineCode,
          taskType,
          status: status,
          statusList: status ? [] : AllStatus,
          actualExecuteStartTime: time?.length ? time[0] : "",
          actualExecuteEndTime: time?.length ? time[1] : "",
          queryType,
          queryQcTask,
        },
        pageNum,
        pageSize,
      };
      getTaskCenterList(params)
        .then((res) => {
          this.list = res.rows || [];
          this.pager.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.list = [];
          this.pager.total = 0;
          this.loading = false;
        });
    },
    getOperatorLabel(row) {
      if (row.operatorType == "dept") {
        // 显示部门
        return row.executiveAgencyName || row.executiveAgency;
      }

      let operatorName = row.operatorName;

      // if (this.postManageDictObj.hasOwnProperty(row.operator)) {
      //   // 显示岗位
      //   operatorName = this.postManageDictObj[row.operator];
      // } else {
      //   // 显示工位
      //   operatorName = row.operatorName;
      // }

      return operatorName || "";
    },
    handleSelectionChange(selection) {
      if (selection.length) {
        // 勾选的数据为待审核的才可以点批量击审核按钮
        const _selection1 = selection.filter(
          (ele) => ele.hasAuditorPower != "Y"
        );
        this.approveBatchDisabled = !!_selection1.length;

        // 勾选的数据有关闭权限的才可以点击批量关闭按钮
        const _selection2 = selection.filter((ele) => ele.hasExecPower != "Y");
        this.closeBatchDisabled = !!_selection2.length;
      } else {
        this.approveBatchDisabled = true;
        this.closeBatchDisabled = true;
      }
    },
    queryParamsChange({ factoryDeptCode, workshopCode, lineCode, lineId }) {
      this.queryParams.factoryDeptCode = factoryDeptCode;
      this.queryParams.workshopCode = workshopCode;
      this.queryParams.lineCode = lineCode;
      this.queryParams.lineId = lineId;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
        time: null,
        queryType: "user", //默认与我相关
        queryQcTask: "",
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addDialog.row = null;
      this.addDialog.visible = true;
      this.addDialog.disabled = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row) {
        row = this.$refs.Table.selection[0] || null;
      }
      this.addDialog.row = row;
      this.addDialog.visible = true;
      this.addDialog.disabled = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = "";
      let msg = "";
      if (row) {
        ids = row.id;
        msg = `确定删除${row.workshopName}吗？`;
      } else {
        const selection = this.$refs.Table.selection;
        ids = selection.map((ele) => ele.id).join(",");
        msg = `确定删除所选的${selection.length}条记录吗？`;
      }
      this.$confirm(msg, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {})
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 执行/审核转办按钮操作 */
    handleTransfer(row) {
      this.transferDailog.row = row;
      this.transferDailog.visible = true;
    },
    /** 执行按钮操作 */
    handleExecute(row) {
      this.executeDailog.row = row;
      this.executeDailog.visible = true;
    },
    /** 审核按钮操作 */
    handleApprove(row) {
      this.approveDailog.row = row;
      this.approveDailog.visible = true;
    },
    handleDetail(row) {
      this.detailDailog.row = row;
      this.detailDailog.visible = true;
    },
    /** 关闭按钮操作 */
    handleClose(row) {
      if (row) {
        this.closeDailog.rows = [row];
      } else {
        const selection = this.$refs.Table.selection;
        // 过滤出有审核权限的数据
        const _selection = selection.filter((ele) => ele.hasExecPower == "Y");
        this.closeDailog.rows = _selection;
      }
      if (!this.closeDailog.rows?.length) {
        this.msgWarning("请选择有关闭权限的任务！");
        return;
      }
      this.closeDailog.visible = true;
    },
    handleApproveBatch() {
      const selection = this.$refs.Table.selection;
      // 过滤出有审核权限的数据
      const _selection = selection.filter((ele) => ele.hasAuditorPower == "Y");

      this.approveTaskBatchDialog.rows = _selection;

      if (!this.approveTaskBatchDialog.rows?.length) {
        this.msgWarning("请选择有审核权限的任务！");
        return;
      }

      this.approveTaskBatchDialog.visible = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportLoading = true;

      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
        time,
        queryType,
        queryQcTask,
      } = this.queryParams;
      const params = {
        taskName,
        ownedFactory: factoryDeptCode,
        ownedWorkshop: workshopCode,
        ownedProductionLine: lineCode,
        taskType,
        status: status,
        statusList: status ? [] : AllStatus,
        actualExecuteStartTime: time?.length ? time[0] : "",
        actualExecuteEndTime: time?.length ? time[1] : "",
        queryType,
        queryQcTask,
      };
      exportTaskList(params)
        .then((res) => {
          downloadFile(
            res.file,
            res.name ||
              `任务中心列表${this.parseTime(new Date(), "{y}{m}{d}")}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .top {
  height: 88px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  .width1 {
    .el-form-item__content {
      width: 142px;
    }
  }
  .width2 {
    .el-date-editor--datetimerange.el-input__inner {
      width: 360px;
    }
  }
  .el-form {
    width: 100%;
    text-align: right;
    height: 48px;
  }
}
::v-deep .organization-cascader {
  display: inline-block;
  vertical-align: middle;
  color: #cccccc;
  .el-form-item {
    margin-bottom: 0;
    .el-form-item__content {
      width: 142px;
    }
  }
}
.pagination-container {
  margin: 0;
}
.status-0,
.status-1 {
  color: #f5b335;
  font-weight: 600;
}
.status-2 {
  color: #d9001b;
  font-weight: 600;
}
.status-3 {
  color: #d9001b;
  font-weight: 600;
}
.status-5 {
  color: #88c446;
  font-weight: 600;
}
</style>
